<?php 
if( !defined( 'WEIXIN_SEARCH' ) ) {
	$weixin_setting	= weixin_get_setting();
	define( 'WEIXIN_SEARCH', $weixin_setting['weixin_search']??false );
}

//如果搜索关键字是分类名或者 tag 名，直接返回该分类或者tag下最新日志
add_filter('weixin_query', function ($weixin_query_array){
	if(isset($weixin_query_array['s'])){
		global $wpdb;
		$keyword = $wpdb->esc_like($weixin_query_array['s']);
		// $term = $wpdb->get_row("SELECT term_id, slug, taxonomy FROM {$wpdb->prefix}term_taxonomy tt INNER JOIN {$wpdb->prefix}terms t USING ( term_id ) WHERE lower(t.name) = '".$wpdb->esc_like($keyword)."' OR t.slug = '".$wpdb->esc_like($keyword)."' LIMIT 0 , 1");
		$term = $wpdb->get_row($wpdb->prepare("SELECT term_id, slug, taxonomy FROM {$wpdb->prefix}term_taxonomy tt INNER JOIN {$wpdb->prefix}terms t USING ( term_id ) WHERE lower(t.name) = %s OR t.slug = %s LIMIT 0 , 1",$keyword,$keyword));

		if($term){
			if($term->taxonomy == 'category'){
				unset($weixin_query_array['s']);
				$weixin_query_array['cat']		= $term->term_id;
			}elseif ($term->taxonomy == 'post_tag') {
				unset($weixin_query_array['s']);
				$weixin_query_array['tag_id']	= $term->term_id;
			}else{
				unset($weixin_query_array['s']);
				$weixin_query_array[$term->taxonomy]	= $term->slug;
			}
			$weixin_query_array = apply_filters('weixin_taxonomy_query',$weixin_query_array,$term);
		}
	}
	return $weixin_query_array;
}, 99);


// 通过自定义字段设置改变图文的链接
// 给用户添加 access_token 或者 openid，用于访问页面时，获取当前用户
add_filter('weixin_url', function($url){
	if($weixin_url = get_post_meta(get_the_ID(), 'weixin_url', true)){
		$url = $weixin_url;
	}

	if(weixin_get_type() == 3){	// 认证订阅号才能加，普通订阅号会出问题，后面不能通过 JS SDK 去掉
		global $weixin_reply;
		return add_query_arg('weixin_access_token', WEIXIN_User::generate_access_token($weixin_reply->get_openid()), $url);
	}
	
	return $url;
}, 99);


// 如果是在被动响应微信消息，和微信用户界面中，设置 is_home 为 false，
add_action('parse_query',function($query){
	if(isset($_GET['weixin']) || isset($_GET['signature']) || !empty($_GET['weixin_user'])) {
		$query->is_home 	= false;
		$query->is_search 	= false;
		$query->is_weixin 	= true;
	}
});